package com.uum.admin.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uum.admin.pojo.entity.SysDict;
import com.uum.admin.pojo.entity.SysDictItem;
import com.uum.admin.pojo.query.DictPageQuery;
import com.uum.admin.service.SysDictItemService;
import com.uum.admin.service.SysDictService;
import com.uum.common.core.annotation.Operation;
import com.uum.common.core.enums.BusinessType;
import com.uum.web.exception.BizException;
import com.uum.common.core.result.Result;
import com.uum.common.core.valid.InsertGroup;
import com.uum.common.core.valid.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "字典接口")
@RestController
@RequestMapping("/api/v1/dict")
@RequiredArgsConstructor
public class SysDictController {
    private final SysDictService sysDictService;
    private final SysDictItemService sysDictItemService;

    @Operation(description = "查询字典列表",businessType = BusinessType.QUERY,isSaveResponseData = false)
    @ApiOperation(value = "字典列表分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "页码", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "name", value = "字典名称", paramType = "query", dataType = "String"),
    })
    @GetMapping("page")
    public Result pageUser(DictPageQuery dictPageQuery) {
        IPage<SysDict> result = sysDictService.page(
                new Page<>(dictPageQuery.getCurrentPage(),dictPageQuery.getPageSize()),
                new LambdaQueryWrapper<SysDict>()
                        .like(StrUtil.isNotBlank(dictPageQuery.getName()), SysDict::getName,dictPageQuery.getName())
                        .orderByDesc(SysDict::getCreateTime));
        return Result.success(result.getRecords(), result.getTotal());
    }

    @ApiOperation(value = "字典列表")
    @GetMapping("list")
    public Result listUser() {
        List<SysDict> list = sysDictService.list(new LambdaQueryWrapper<SysDict>().orderByDesc(SysDict::getCreateTime));
        return Result.success(list);
    }

    @ApiOperation(value = "字典详情")
    @ApiImplicitParam(name = "id", value = "字典id", required = true, paramType = "path", dataType = "Long")
    @GetMapping("/detail/{id}")
    public Result dictDetail(@PathVariable Integer id) {
        SysDict dict = sysDictService.getById(id);
        return Result.success(dict);
    }

    @Operation(description = "新增字典",businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增字典")
    @ApiImplicitParam(name = "dictItem", value = "实体JSON对象", required = true, paramType = "body", dataType = "SysDictItem")
    @PostMapping("add")
    public Result addDict(@Validated(InsertGroup.class) @RequestBody SysDict dict) {
        boolean status = sysDictService.save(dict);
        return Result.judge(status);
    }

    @Operation(description = "修改字典",businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改字典")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictItem", value = "实体JSON对象", required = true, paramType = "body", dataType = "SysDictItem")
    })
    @PutMapping(value = "update")
    public Result updateDict(@Validated(UpdateGroup.class) @RequestBody SysDict dict) {
        //更新前获取code
        SysDict dbDict = sysDictService.getById(dict.getId());
        boolean status = sysDictService.updateById(dict);
        if (status) {
            // 判断有无更新code
            if (!StrUtil.equals(dbDict.getCode(), dict.getCode())) {
                // 字典code更新，同步更新字典项code
                sysDictItemService.update(new LambdaUpdateWrapper<SysDictItem>().eq(SysDictItem::getDictCode, dbDict.getCode())
                        .set(SysDictItem::getDictCode, dict.getCode()));
            }
        }
        return Result.judge(status);
    }

    @Operation(description = "删除字典",businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除字典")
    @ApiImplicitParam(name = "ids", value = "以,分割拼接字符串", required = true, paramType = "query", dataType = "String")
    @DeleteMapping("delete/{ids}")
    public Result deleteDict(@PathVariable String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<String> codeList = sysDictService.listByIds(idList).stream().map(item -> item.getCode()).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(codeList)) {
            int count = sysDictItemService.count(new LambdaQueryWrapper<SysDictItem>().in(SysDictItem::getDictCode, codeList));
            if (count > 0) {
                throw new BizException("删除字典失败，请先删除关联字典数据");
            }
        }
        boolean status = sysDictService.removeByIds(idList);
        return Result.judge(status);
    }

}

